import logging, os, time, traceback


class Log(object):
    def __init__(self, log_name, msg_pre=''):
        # 日志文件夹名
        self.log_name = log_name
        # 消息前缀
        self.msg_pre = msg_pre
        # 日志保存的位置
        self.path = os.path.abspath(os.path.dirname(__file__)).split("lib")[0] + '/log/' + self.log_name + '/'
        # 格式化输出
        self.formatter = logging.Formatter(
            "\ntime:%(asctime)s \t nfile:%(filename)s \t fun:%(funcName)s \t lineno:%(lineno)d \nmessage:%(message)s")

        # 初始化log
        self.logger = logging.getLogger(self.log_name)
        # 设置日志等级
        self.logger.setLevel(logging.DEBUG)

        # 控制台打印
        ch = logging.StreamHandler()
        # 设置打印等级
        ch.setLevel(logging.WARNING)
        # 格式化打印
        ch.setFormatter(self.formatter)
        # 增加处理handler
        self.logger.addHandler(ch)

        # 文件写入
        self.fileHandlerName = ''
        self.fileHandler = None

    def setfh(self):
        _fileName = time.strftime("%Y%m%d%H")
        # 每小时一个log文件
        if _fileName != self.fileHandlerName:
            # 移除原来的handler
            if self.fileHandler is not None:
                self.logger.removeHandler(self.fileHandler)
            # 创建文件夹
            if not os.path.isdir(self.path):
                os.makedirs(self.path)

            # 文件写入处理
            _fileHandler = logging.FileHandler(self.path + _fileName + '.log')
            # 设置写入等级
            _fileHandler.setLevel(logging.DEBUG)
            # 格式化输出
            _fileHandler.setFormatter(self.formatter)
            self.logger.addHandler(_fileHandler)

            self.fileHandlerName = _fileName
            self.fileHandler = _fileHandler

    # 格式化日志内容
    def _fmtInfo(self, msg):
        if len(msg) == 0:
            msg = traceback.format_exc()
            return self.msg_pre + ' ' + msg
        else:
            _tmp = [
                self.msg_pre + ' ' + str(msg[0]),
                # traceback.format_exc()
            ]
            return '\nsysErrmsg:'.join(_tmp)

    def debug(self, *msg):
        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.debug(_info)
        except:
            print('mylog debug:' + _info)

    def error(self, *msg):
        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.error(_info)
        except:
            print('mylog error:' + _info)

    def info(self, *msg):
        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.info(_info)
        except:
            print('mylog info:' + _info)

    def warning(self, *msg):
        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.warning(_info)
        except:
            print('mylog warning:' + _info)


if __name__ == '__main__':
    log = LOG('gamelog')
    try:
        print(1 / 0)

    except:
        log.error()  # 使用系统自己的错误描述

    time.sleep(2)

    try:
        print(2 / 0)
    except:
        log.error('搞错了，分母不能为0')  # 使用自己的错误描述
